package com.dynamic.mybatis.bootstrap.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.fastjson.JSON;
import com.dynamic.mybatis.bootstrap.mapper.BaseMapper;
import com.dynamic.mybatis.bootstrap.vo.DynamicDataSourceVo;
import com.dynamic.mybatis.bootstrap.vo.DynamicMappedStatementVo;
import com.dynamic.mybatis.core.datasource.DataSourceProperty;
import com.dynamic.mybatis.core.metadata.DynamicMappedStatement;
import com.dynamic.mybatis.core.parser.NamespaceHelper;
import com.dynamic.mybatis.core.session.DynamicSqlSessionTemplate;
import com.dynamic.mybatis.core.toolkit.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
public class MappedStatementInitializeRunner  implements ApplicationRunner {
    @Autowired
    BaseMapper baseMapper;
    @Autowired
    DynamicSqlSessionTemplate dynamicSqlSessionTemplate;

    @Override
    public void run(ApplicationArguments args) {
        new Thread(()->{
            List<DynamicDataSourceVo> dds =  baseMapper.queryDatasource();
            initDatasource(dds);

            List<DynamicMappedStatementVo> dms =  baseMapper.queryMappedStatement();
            initMappedStatement(dms);
        }).start();
    }


    public void initMappedStatement(List<DynamicMappedStatementVo> dms){
       if(dms == null ){return;}
        List<DynamicMappedStatement> list =   dms.stream().map(ms ->
             new DynamicMappedStatement().toBuilder()
                   .setUid(String.valueOf(ms.getId()))
                   .setShortId(ms.getCode())
                   .setName(ms.getName())
                   .setCommandType(ms.getCommandType())
                   .setNamespace(ms.getNamespace())
                   .setSqlStatement(ms.getSqlStatement())
                   .setResultType(ms.getReturnType())
                   .setReturnType(ms.getReturnType())
                   .setDynamicDataSourceKeys(ms.getDataSourceCodes().split(","))
                   .builder()
       ).collect(Collectors.toList());
       dynamicSqlSessionTemplate.getDynamicMappedStatementHelper().addParseDynamicMappedStatement(list);
    }

    public void initDatasource(List<DynamicDataSourceVo> dds){
        dds.stream().forEach( ds ->{
            String key = NamespaceHelper.getIdentity(ds.getNamespace(),ds.getCode());
            DruidDataSource dataSource = new DruidDataSource();
            dataSource.setUrl(ds.getUrl());
            dataSource.setUsername(ds.getUsername());
            dataSource.setPassword(ds.getPassword());
            dataSource.setDriverClassName(ds.getDriverClass());
            DataSourceProperty property = BeanUtils.copy(ds,new DataSourceProperty());
            property.setUid(String.valueOf(ds.getId()));
            Map attributes = JSON.parseObject(ds.getAttributes());

            dynamicSqlSessionTemplate.addDataSource(key,dataSource,property,attributes);
        });
    }
}
